<script setup>
import request from "@/utils/request.js";
import { ref, onMounted, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useUserStore } from '@/stores/user';
// 导入图标组件
import { Menu, Document, User, SwitchButton } from '@element-plus/icons-vue';

const router = useRouter();
const userStore = useUserStore();
const activeIndex = ref('/rider/orders');
const riderInfo = ref({});

// 从Pinia获取用户信息
const userInfo = computed(() => userStore.user || {});

// 获取骑手信息
const getRiderInfo = async () => {
  try {
    if (userStore.userId) {
      const { data: res } = await request.get(`/rider/user/${userStore.userId}`);
      if (res) {
        riderInfo.value = res;
      }
    }
  } catch (error) {
    console.error('获取骑手信息失败', error);
    ElMessage.error('获取骑手信息失败');
  }
};

// 处理菜单点击
const handleSelect = (index) => {
  router.push(index);
};

// 处理图片URL
const getImgUrl = (url) => {
  if (!url) return '';

  // 确保有服务器地址前缀
  const serverBaseUrl = import.meta.env.VITE_API_BASE_URL || '';
  let fullUrl = url;

  if (url.startsWith('/uploads/')) {
    fullUrl = serverBaseUrl + url;
  } else if(url.startsWith('uploads/')) {
    fullUrl = serverBaseUrl + '/' + url;
  }

  return fullUrl;
};

// 退出登录
const logout = async () => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm('确定要退出登录吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false,
      closeOnPressEscape: false,
      closeOnHashChange: false
    });
    
    try {
      // 调用后端退出登录接口
      await request.post('/logout', { userId: userStore.userId });
    } catch (error) {
      console.error('退出登录接口调用失败:', error);
      // 即使接口调用失败，也继续执行前端登出逻辑
    }
    
    // 清除本地存储
    localStorage.removeItem('user');
    localStorage.removeItem('token');
    
    // 清除Pinia状态
    userStore.logout();
    
    ElMessage.success('退出登录成功');
    
    // 跳转到登录页
    router.push('/login');
  } catch (error) {
    // 用户取消退出操作
    console.log('用户取消退出', error);
  }
};

// 监听路由变化
watch(
  () => router.currentRoute.value.path,
  (newPath) => {
    activeIndex.value = newPath;
  }
);

onMounted(() => {
  // 根据当前路由设置激活菜单
  activeIndex.value = router.currentRoute.value.path;
  getRiderInfo();
});
</script>

<template>
<el-container class="rider-center">
  <el-header class="rider-header">
    <el-link :underline="false" :href="'/'" style="color: white;float: left;width: auto;height: 100%">
      <h1 style="height: 100%">骑手配送系统</h1>
    </el-link>
    <div class="user-info" v-if="userStore.username">
      <el-dropdown>
        <span class="el-dropdown-link">
          <el-avatar 
            v-if="riderInfo.avatar" 
            :size="45" 
            :src="getImgUrl(riderInfo.avatar)" 
            class="user-avatar"
          ></el-avatar>
          <el-avatar 
            v-else 
            :size="45" 
            class="user-avatar"
          >{{ userStore.username.charAt(0).toUpperCase() }}</el-avatar>
          <span class="username">{{ userStore.username }}</span>
          <i class="el-icon-arrow-down el-icon--right"></i>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="router.push('/rider/info')">个人信息</el-dropdown-item>
            <el-dropdown-item divided @click="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </el-header>
  <el-container class="rider-container" style="overflow: hidden">
    <el-aside width="200px">
      <el-menu
        :default-active="activeIndex"
        class="el-menu-vertical"
        @select="handleSelect"
        router
      >
        <el-menu-item index="/rider/orders">
          <el-icon><Menu /></el-icon>
          <span>订单大厅</span>
        </el-menu-item>
        <el-menu-item index="/rider/history">
          <el-icon><Document /></el-icon>
          <span>历史订单</span>
        </el-menu-item>
        <el-menu-item index="/rider/info">
          <el-icon><User /></el-icon>
          <span>个人中心</span>
        </el-menu-item>
        <el-menu-item @click="logout">
          <el-icon><SwitchButton /></el-icon>
          <span>退出登录</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <el-main>
      <router-view></router-view>
    </el-main>
  </el-container>
</el-container>
</template>

<style scoped>
.rider-center {
  height: 100vh;
  width: 100%;
}

.rider-header {
  background-color: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30px;
  height: 74.5px;
}

.user-info {
  display: flex;
  align-items: center;
}

.el-dropdown-link {
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.user-avatar {
  margin-right: 8px;
}

.username {
  font-size: 18px;
  margin-right: 4px;
}

.el-aside {
  background-color: #f0f2f5;
}

.el-menu {
  border-right: none;
  height: 100%;
}

.el-menu-vertical {
  border-right: #ddd 1px solid;
  width: 200px;
}
</style>